package com.lw.leetcode.binary.a;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1337. 矩阵中战斗力最弱的 K 行
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/2 9:54
 */
public class KWeakestRows {

    public static void main(String[] args) {
        KWeakestRows test = new KWeakestRows();

        // [[1,1,0,0,0],[1,1,1,1,0],[1,0,0,0,0],[1,1,0,0,0],[1,1,1,1,1]] 3   [2,0,3]
        int[][] arr = {{1, 1, 0, 0, 0}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {1, 1, 0, 0, 0}, {1, 1, 1, 1, 1}};
        int k = 3;

        // [[1,1,1,1,1],[1,0,0,0,0],[1,1,0,0,0],[1,1,1,1,0],[1,1,1,1,1]] 3   [1,2,3]
//        int[][] arr = {{1,1,1,1,1}, {1,0,0,0,0},{1,1,0,0,0},{1,1,1,1,0},{1,1,1,1,1}};
//        int k = 3;


        int[] ints = test.kWeakestRows(arr, k);
        System.out.println(Arrays.toString(ints));

    }

    public int[] kWeakestRows(int[][] mat, int k) {
        int length = mat.length;
        int[][] item = new int[length][2];
        for (int i = 0; i < length; i++) {
            item[i][0] = find(mat[i]);
            item[i][1] = i;
        }
        Arrays.sort(item, (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);

        int[] values = new int[k];
        for (int i = 0; i < k; i++) {
            values[i] = item[i][1];
        }
        return values;
    }

    private int find(int[] arr) {
        int end = arr.length - 1;
        if (arr[end] == 1) {
            return end + 1;
        }
        int st = 0;
        while (st < end) {
            int m = st + ((end - st) >> 1);
            if (arr[m] == 1) {
                st = m + 1;
            } else {
                end = m;
            }
        }
        return st;
    }
}
